#include "Energy.h"

module StateTestP {
	
	uses {
		interface Boot;
		interface EnergyState;
		interface EnergyFlags;
		interface Alarm<T32khz,uint32_t>;
		interface Leds;
		interface GeneralIO as Pin;
	}

} implementation{	

	enum {
		NUMBER_STATES = 4,
		PERIOD = 32768, // 32768
	};

	energy_state_t state;
	uint32_t lastAlarm;

	event void Boot.booted() {
		state = ENERGY_STATE1;
		call Pin.makeOutput();
		call Pin.set();
		call Alarm.start(0);
	}			

	async event void Alarm.fired(){
		atomic {
			lastAlarm = call Alarm.getNow();
			state = (energy_state_t) ((state + 1) % NUMBER_STATES);
			//state = ENERGY_STATE4;
			if(call EnergyState.setState(state) != SUCCESS) {
				call Leds.led0On();
				call Leds.led1On();
				call Leds.led2On();
				call Alarm.stop();
			} else {
				call Leds.set(state);
				call Alarm.startAt(lastAlarm, PERIOD);
			}
		}
	}
}
